package com.qf.system.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.common.base.result.ResponseResult;
import com.qf.common.base.result.ResultCode;
import com.qf.system.config.MsgProperites;
import com.qf.system.reqeust.MemberParam;
import com.qf.system.reqeust.MsgTemplateParam;
import com.qf.system.service.MsgService;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;

@Service
public class MsgServiceImpl implements MsgService {

    public static final String PREFIX_REDIS_KEY = "msg:phone:";
    @Resource
    MsgProperites msgProperites;
    @Resource
    IAcsClient client;
    @Resource
    ValueOperations<String, Object> valueOperations;
    @Resource
    ObjectMapper objectMapper;

    @Override
    public ResponseResult sendMsg(String phone) {
        /**
         * 随机生成 6 位数的验证码
         */
        String number = RandomUtil.randomNumbers(6);
        /**
         * new 一个 param 存放随机生成的验证码
         */
        MsgTemplateParam msgTemplateParam = new MsgTemplateParam();
        msgTemplateParam.setCode(number);
        /**
         * 提取出要发验证码的手机号码
         * 获得 SignName , TemplateCode 和 验证码
         */
        SendSmsRequest request = new SendSmsRequest();
        request.setSignName(msgProperites.getSignName());
        request.setTemplateCode(msgProperites.getTemplateCode());
        request.setPhoneNumbers(phone);
        try {
            request.setTemplateParam(objectMapper.writeValueAsString(msgTemplateParam));
            SendSmsResponse response = client.getAcsResponse(request);
            /**
             * 判断是否发送成功
             */
            if ("OK".equals(response.getCode())) {
                /**
                 * 规定验证码的有效时长
                 */
                valueOperations.set(PREFIX_REDIS_KEY + phone, number, Duration.ofMinutes(10));
            }
        }catch (ClientException | JsonProcessingException e){
            return ResponseResult.error(ResultCode.AUTH_ERROR);
        }
        return ResponseResult.success(ResultCode.SUCCESS);
    }
}
